#!/usr/bin/python -tt
import sys, Image, ImageDraw, os, re

def find_images(source):
  
  sourcefiles = os.listdir(source)
  imagefiles = []
  for i in range(len(sourcefiles)):
    match = re.search(r'\w[\s\w\(\)-]+\.jpg', str(sourcefiles), re.I)
    if not match:
      match = re.search(r'\w[\s\w\(\)-]+\.gif', str(sourcefiles), re.I)
    if not match:
      match = re.search(r'\w[\s\w\(\)-]+\.jpeg', str(sourcefiles), re.I)
    if not match:
      match = re.search(r'\w[\s\w\(\)-]+\.png', str(sourcefiles), re.I)
    if match:
      a = sourcefiles.index(match.group())
      sourcefiles.pop(a)
      if match.group() in imagefiles:
        a = 1
      else:
        imagefiles.append(match.group())
  print '\nFound ' + str(len(imagefiles)) + ' image files!'
  return imagefiles

def folders(paths):
  if len(paths) == 2:
    cd = paths[1]
  else:
    cd = os.getcwd()
  pathtwo = os.path.join(cd, 'squarified')
  if not os.path.exists(pathtwo):
    os.makedirs(pathtwo)
    print 'Output folder does not exist and will be created'
  path = os.path.abspath(paths[0])
  if path == pathtwo:
    print "\nPlease specify a different output directory!\n- This is to avoid destroying your originals..."
  print '\nSource Directory: ' + path
  print 'Default Output Directory: ' + pathtwo    
  return [path, pathtwo]

def process_images(paths, fname):
  for f in fname:
    fullname = os.path.join(paths[0], f)
    fullnameout = os.path.join(paths[1], f)
    im = Image.open(fullname)
    x, y = im.size
    if x > y:
      background = Image.new('RGB', (x, x), '#FFFFFF')
      background.paste(
        im,
        (0, (x - y) / 2))
    elif y > x:
      background = Image.new('RGB', (y, y), '#FFFFFF')
      background.paste(
        im,
        ((y - x) / 2, 0))
    elif x == y:
      background = im
    x, y = background.size
    if x > 850:
      image = background.resize((850, 850), Image.ANTIALIAS)
    else:
      image = background
    image.save(fullnameout[:-3] + 'jpg', "JPEG") 


def main():
  dir = sys.argv
  del dir[0]
  if len(dir) == 0:
    print "\nPlease specify a source directory\nFor Example: image.py " +  os.getcwd() + "\n\nYou may also specify an input followed by an ouput directory\nFor Example: image.py " +  os.getcwd() + " " + os.path.join(os.getcwd(), 'squarified')
    sys.exit(0)
  elif len(dir) <= 2:
    paths = folders(dir)
    imagefiles = find_images(paths[0])
    if len(imagefiles) > 0:
      print '\n\nProcessing...',
      process_images(paths, imagefiles)
      print 'Done'
    sys.exit(0)
  else:
    print "\nInput unknown!\n\nPlease specify a source directory\nFor Example: image.py " +  os.getcwd() + "\n\nYou may also specify an input followed by an ouput directory\nFor Example: image.py " +  os.getcwd() + " " + os.path.join(os.getcwd(), 'squarified')
    sys.exit(0)
if __name__ == '__main__':
  main()
